package com.airticketbooking.task;


import com.airticketbooking.common.constant.StatusConstant;
import com.airticketbooking.mapper.*;
import com.airticketbooking.po.FlightSchedule;
import com.airticketbooking.po.Seat;
import com.airticketbooking.po.Ticket;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;


@RequiredArgsConstructor
@Component
@Slf4j
public class TicketTask {


	private final FlightScheduleMapper flightShceduleMapper;

	private final TicketMapper ticketMapper;

	private final SeatMapper seatMapper;

	private final FlightMapper flightMapper;


	//	TODO:进行redis优化，减少查询次数
	//	处理flIghtSchedule表中状态改变了的班次，对应的票据状态也要改变
	@Scheduled(cron = "0 * * * * *")//每隔一分钟触发一次
	public void processFlIghtScheduleStatusChange() {

		List<FlightSchedule> flightSchedules = flightShceduleMapper.getAll();


		for (FlightSchedule flightSchedule : flightSchedules) {

			Integer scheduleId = flightSchedule.getScheduleId();
			Integer fstatus = flightSchedule.getStatus();


			Integer airplaneId = flightMapper.getAirplaneIdById(flightSchedule.getFlightId());


			List<Ticket> tickets = ticketMapper.getTicketByScheduleId(scheduleId);


			if (fstatus == StatusConstant.SCHEDULE_AVAILABLE) {

				for (Ticket ticket : tickets) {

					if (ticket.getStatus() == StatusConstant.DISABLE) {
						ticket.setScheduleId(scheduleId);
						ticket.setStatus(StatusConstant.TICKET_COULD_BOOK);
						ticket.setUpdateTime(LocalDateTime.now());
						ticketMapper.update(ticket);
					}
				}

			} else if (fstatus == StatusConstant.SCHEDULE_DELAY || fstatus == StatusConstant.SCHEDULE_DEPART) {

				for (Ticket ticket : tickets) {

					if (ticket.getStatus() == StatusConstant.TICKET_COULD_BOOK) {
						ticket.setScheduleId(scheduleId);
						ticket.setStatus(StatusConstant.DISABLE);
						ticket.setUpdateTime(LocalDateTime.now());
						ticketMapper.update(ticket);
					}
				}
			} else if (fstatus == StatusConstant.SCHEDULE_ARRIVED) {

				for (Ticket ticket : tickets) {


					ticket.setScheduleId(scheduleId);
					ticket.setStatus(StatusConstant.TICKET_FINISHED);
					ticket.setUpdateTime(LocalDateTime.now());
					ticketMapper.update(ticket);
				}


				List<Seat> seats = seatMapper.getSeatsByAirplaneIdAndWithoutStatus(airplaneId);

//				更新座位状态为可用
				if (seats.get(0).getStatus() == StatusConstant.DISABLE) {
					Seat seat = new Seat();
					seat.setAirplaneId(airplaneId);
					seat.setStatus(StatusConstant.ENABLE);
					seatMapper.updateSeat(seat);
				}
			}

		}


	}
}
